package com.xgzit.xgzmall.ware.listener;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.xgzit.common.dto.mq.OrderDto;
import com.xgzit.common.dto.mq.StockDetailDto;
import com.xgzit.common.dto.mq.StockLockedDto;
import com.xgzit.common.utils.R;
import com.xgzit.xgzmall.ware.dao.WareSkuDao;
import com.xgzit.xgzmall.ware.entity.WareOrderTaskDetailEntity;
import com.xgzit.xgzmall.ware.entity.WareOrderTaskEntity;
import com.xgzit.xgzmall.ware.feign.OrderFeignService;
import com.xgzit.xgzmall.ware.service.WareOrderTaskDetailService;
import com.xgzit.xgzmall.ware.service.WareOrderTaskService;
import com.xgzit.xgzmall.ware.service.WareSkuService;
import com.xgzit.xgzmall.ware.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

/**
 * @Author xgz
 * @Date 2021-07-05 22:31
 */
@Service
@Slf4j
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    WareOrderTaskService orderTaskService;
    /**
     * 1、库存自动解锁
     *   下订单过程 创建订单号，订单项成功，库存锁定成功，但是下订单过程中  之后的调用其他业务如 积分扣减失败 导致下订单回滚
     *    之前锁定的库存就要解锁。
     * 2、订单失败
     *    锁库存失败
     *
     *只要解锁库存消息失败 一定要告诉服务器解锁失败，
     *
     * @param dto:
     * @param message:
     * @return void
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedDto dto, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(dto);
            // 解锁成功才告诉 mq 收到消息  basicAck 第二个参数： 是否批量模式
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("解锁库存异常", e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
    * 处理 主动关闭订单 成功发送来的消息
    * @param dto:
    * @param message:
    * @param channel:
    * @return void
    */
    @RabbitHandler
    public void handleOrderClose(OrderDto dto, Message message, Channel channel) throws IOException {
        log.info("收到订单关闭准备解锁库存的消息");
        try {
            wareSkuService.unlockStock(dto);
            // 解锁成功才告诉 mq 收到消息  basicAck 第二个参数： 是否批量模式
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("解锁库存异常", e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }


}
